﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using XML;

namespace TestOldApplication
{
	/// <summary>
	/// Класс, реализующий метод запуска приложения.
	/// </summary>
	public class ApplicationRun
	{
		private string currentDirectoryApplication;
		private List<FileInfo> files;
		private bool runUpdate;
		private string[] args;
		private FileInfo config;
		private FileInfo updater;
        private string applicationPath;
        private string processName;
		/// <summary>
		/// Конструктор
		/// </summary>
		/// <param name="args">Параметры</param>
		/// <param name="currentDirectoryApplication">Путь к текущей рабочей папке.</param>
		public ApplicationRun(string[] args)
		{
			currentDirectoryApplication = Environment.CurrentDirectory;
			this.args = args;
			runUpdate = true;
			files = new DirectoryInfo(currentDirectoryApplication).GetFiles(".", SearchOption.AllDirectories).ToList();
			config = files.Find(p => p.Name == "Updater.exe.config");
			updater = files.Find(p => p.Name == "Updater.exe");
            applicationPath = System.Reflection.Assembly.GetExecutingAssembly().Location;
            processName = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name;
		}

		/// <summary>
		/// Запуск приложения.
		/// </summary>
		public void RunApplication()
		{
			OparationWithConfig();
			SetConditionRunUpdate();
			RunUpdate();
		}

		private void RunUpdate()
		{
			if (updater != null)
			{
				if (runUpdate)
				{
					Process.Start(updater.FullName);
				}
			}
			else
			{
				throw new ApplicationException("Updater.exe не найден.");
			}
		}

		private void SetConditionRunUpdate()
		{
			if (args.Count() != 0)
			{
				if (args[0] == "new")
				{
					runUpdate = false;
				}
			}
		}

		private void OparationWithConfig()
		{
			if (config != null)
			{
				WriteSettingsToConfig();
			}
		}

		private void WriteSettingsToConfig()
		{
			ForXmlFiles.SetConfigurationField(config.FullName, "TargetPath", currentDirectoryApplication);            
			ForXmlFiles.SetConfigurationField(config.FullName, "appToStart", applicationPath);
			ForXmlFiles.SetConfigurationField(config.FullName, "processToFinish", processName);
		}
	}
}
